//
//  RootViewController.m
//  Finder
//
//  Created by cdm on 11-3-16.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "RootViewController.h"
#import "ContentViewController.h"
#import "UtilitiesViewController.h"
#import "RecommendViewController.h"
#import "SuggestionViewController.h"
#import "WebBrowserController.h"
#import "ApplicationContext.h"
#import "Menu.h"
#import "ShareSetting.h"
#import "DeviceUtil.h"
#import "WebBrowserController.h"
#import "AppLanguage.h"
#import "RegisterViewController.h"

@interface RootViewController ()

@property (nonatomic, retain) ShareSetting *shareSetting;
@property (nonatomic, retain) NSMutableArray *menus;

- (void)loadMenus;
- (void)initLocalization;
- (void)appLocaleDidChange;
- (void)promptToRegister;
- (void)appLanguageDidChange;

@end


@implementation RootViewController

@synthesize shareSetting;
@synthesize menus;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [self.shareSetting release];
    [self.menus release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self loadMenus];
    
    // 添加分享按钮
    UIBarButtonItem *shareButtonItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStyleBordered target:self action:@selector(shareButtonItemOnClick:)];
    self.navigationItem.rightBarButtonItem = shareButtonItem;
    [shareButtonItem release];
    
    // 添加乐享网站访问按钮
    UIBarButtonItem *websiteButtonItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStyleBordered target:self action:@selector(websiteButtonItemOnClick:)];
    self.navigationItem.leftBarButtonItem = websiteButtonItem;
    [websiteButtonItem release];
    
    //设置TabBar
    NSMutableArray *showControllers = [[NSMutableArray alloc] init];
    
    Menu *menu1 = [self.menus objectAtIndex:0];
    if (menu1.isShow) {
        ContentViewController *contentViewController = [[ContentViewController alloc] initWithNibName:@"ContentView" bundle:nil];
        contentViewController.tabBarItem.title = menu1.name;
        contentViewController.tabBarItem.image = [UIImage imageNamed:@"ic_home.png"];
        contentViewController.title = menu1.name;
        
        [showControllers addObject:contentViewController];
        
        [contentViewController release];
    }
        
    Menu *menu2 = [self.menus objectAtIndex:1];
    if (menu2.isShow) {
        UtilitiesViewController *utilitiesViewController = [[UtilitiesViewController alloc] initWithNibName:@"UtilitiesView" bundle:nil];
        utilitiesViewController.tabBarItem.title = menu2.name;
        utilitiesViewController.tabBarItem.image = [UIImage imageNamed:@"ic_tools.png"];
        utilitiesViewController.title = menu2.name;
        
        [showControllers addObject:utilitiesViewController];
        
        [utilitiesViewController release];
    }
    
    Menu *menu3 = [self.menus objectAtIndex:2];
    if (menu3.isShow) {
        RecommendViewController *recommendViewController = [[RecommendViewController alloc] initWithNibName:@"RecommendView" bundle:nil];
        recommendViewController.tabBarItem.title = menu3.name;
        recommendViewController.tabBarItem.image = [UIImage imageNamed:@"ic_star.png"];
        recommendViewController.title = menu3.name;
        
        [showControllers addObject:recommendViewController];
        
        [recommendViewController release];
    }
    
    Menu *menu4 = [self.menus objectAtIndex:3];
    if (menu4.isShow) {
        SuggestionViewController *suggestionViewController = [[SuggestionViewController alloc] initWithNibName:@"SuggestionView" bundle:nil];
        suggestionViewController.tabBarItem.title = menu4.name;
        suggestionViewController.tabBarItem.image = [UIImage imageNamed:@"ic_chat.png"];
        suggestionViewController.title = menu4.name;
        
        [showControllers addObject:suggestionViewController];
        
        [suggestionViewController release];
    }
    
    self.viewControllers = showControllers;
    [showControllers release];
    
    // 初始化分享设置
    self.shareSetting = [ShareSetting settingFromPlist:@"ShareSetting.plist"];
    
    // 国际化
    [self initLocalization];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appLocaleDidChange) name:kAppLanguageChangedNotification object:nil];
    
    // 提示注册
    if (![ApplicationContext sharedContext].appSetting.registered) {
        [self promptToRegister];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appLanguageDidChange) name:kAppLanguageChangedNotification object:nil];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
//    self.shareButtonItem = nil;
//    self.websiteButtonItem = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Action sheet delegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        if ([DeviceUtil canSendSMS]) {
            MFMessageComposeViewController *messageController = [[MFMessageComposeViewController alloc] init];
            messageController.messageComposeDelegate = self;
            messageController.body = self.shareSetting.content;
            [self presentModalViewController:messageController animated:YES];
            [messageController release];
        } else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"您使用的设备无法发送短信" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [alertView release];
        }
        
    } else if (buttonIndex == 1) {
        if ([DeviceUtil canSendMail]) {
            MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc] init];
            mailController.mailComposeDelegate = self;
            [mailController setSubject:self.shareSetting.content];
            [mailController setMessageBody:self.shareSetting.content isHTML:YES];
            
            [self presentModalViewController:mailController animated:YES];
            [mailController release];
        } else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"您使用的设备无法发送邮件" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [alertView release];

        }
  
    } else if (buttonIndex == [actionSheet numberOfButtons] - 1) {
        
    } else {
        int selectedTweetIndex = buttonIndex - 2;
        Tweet *tweet = [self.shareSetting.tweets objectAtIndex:selectedTweetIndex];
        
        NSString *url = [NSString stringWithFormat:@"%@&title=%@", tweet.url, self.shareSetting.content];
        NSString *encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        WebBrowserController *webBrowserController = [[WebBrowserController alloc] initWithNibName:@"WebBrowser" bundle:nil];
        [webBrowserController loadWithURL:encodedUrl];
        [self presentModalViewController:webBrowserController animated:YES];
        [webBrowserController release];
    } 
}

#pragma mark - MFMessage compose delegate

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - MFMail compose deleate

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error 
{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark Event

- (IBAction)shareButtonItemOnClick:(id)sender
{
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择分享方式" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];


    [actionSheet addButtonWithTitle:@"短信"];
    [actionSheet addButtonWithTitle:@"邮件"];
    for (Tweet *tweet in self.shareSetting.tweets) {
        [actionSheet addButtonWithTitle:tweet.name];
    }
    [actionSheet addButtonWithTitle:@"取消"];
    
    actionSheet.cancelButtonIndex = actionSheet.numberOfButtons - 1;

    [actionSheet showInView:self.view];
    [actionSheet release];
}

- (IBAction)websiteButtonItemOnClick:(id)sender
{
    RegisterViewController *controller = [[RegisterViewController alloc] initWithNibName:@"RegisterView" bundle:nil];
    [self presentModalViewController:controller animated:YES];
    [controller release];
}

#pragma mark - Load menus
- (void)loadMenus
{
    NSMutableArray *data = [Menu menusFromPlist:@"MenuData.plist"];
    self.menus = data;
}

#pragma mark - Localization

- (void)initLocalization
{
    
    [self loadMenus];
    
    for (int i = 0; i < 4; i++) {
        Menu *menu = [self.menus objectAtIndex:i];
        UIViewController *controller = [self.viewControllers objectAtIndex:i];
        
        controller.tabBarItem.title = menu.name;
        controller.title = menu.name;
    }
    
    self.navigationItem.leftBarButtonItem.title = [AppLanguage getString:@"LeXiangPassport"];
    self.navigationItem.rightBarButtonItem.title = [AppLanguage getString:@"Share"];

}

#pragma mark - App locale change

- (void)appLocaleDidChange
{
    [self initLocalization];
}

#pragma mark - Prompt to register

- (void)promptToRegister
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"注册乐享通行证" message:@"你还未注册乐享通行证。注册乐享通行证，可以享受乐享会员服务，是否现在注册?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
    [alertView release];
}

#pragma mark - Alert View delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        RegisterViewController *controller = [[RegisterViewController alloc] initWithNibName:@"RegisterView" bundle:nil];
        [self presentModalViewController:controller animated:YES];
        [controller release];
    }
}

#pragma mark - App Language

- (void)appLanguageDidChange
{
    self.shareSetting = [ShareSetting settingFromPlist:@"ShareSetting.plist"];
}

@end
